import { defineStore } from "pinia";
import { toRaw } from "vue";
import { store } from "@/store";
import { getGiftsList } from '@/api/gift'
import { storageLocal } from "@pureadmin/utils";

const store_id = 'gift-list'

export const useGiftStore = defineStore({
    id: 'gift-list',
    state: () => ({
        gift_list: storageLocal().getItem(store_id) ?? []
    }),
    actions: {
        setGiftList(gift_list) {
            this.gift_list = gift_list
        },
        /** 通过id获取指定商品信息 */
        getGiftById(goodsId) {
            let giftList = toRaw(this.gift_list)
            return giftList.find(item => item.goodsid === Number(goodsId));
        },
        /** 获取所有商品信息 */
        async getAllGifts() {
            const res = await getGiftsList();
            storageLocal().setItem(store_id, res.data)
            this.setGiftList(res.data);
            return this.gift_list
        }
    }
})

export function useGiftStoreHook() {
    return useGiftStore(store);
}